{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet"
          href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}"
          xmlns="http://www.w3.org/1999/html">
    <!-- Select2 -->
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'modaal/css/modaal.min.css' %}">
    <style>
        /* dataTables列内容居中 */
        #proj-list > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #proj-list > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        ul.parsley-errors-list {
            list-style-type: none;
            color: red;
            padding-left: 0;
            margin-bottom: 0;
        }
    </style>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
{% endblock %}

{% block content %}

    <div class="row">
        <div class="col-sm-7 pull-left" style="margin-bottom: 3px">
            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" data-target="#ProjectModal"
                    id="add-proj">
                <i class="fa fa-plus-square"></i>
                <span class="bigger-110">新增项目</span>
            </button>
        </div>

        <!--dataTable-->
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box">
                <div class="box-body">
                    <table id="proj-list" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th>项目名称</th>
                            <th>项目环境</th>
                            <th>产品名称</th>
                            <th>项目负责人</th>
                            <th>项目成员</th>
                            <th>项目备注</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for project in projects %}
                            <tr>
                                <td>{{ project.project_name }}</td>
                                <td>
                                    <span class="badge bg-green">{{ project.get_project_env_display }}</span>
                                </td>
                                <!--td>{{ project.project_web|default:'' }}</td-->
                                <td>{{ project.project_product.product_name|default:'' }}</td>
                                <td>{{ project.project_admin.username }}</td>
                                <td>{{ project.project_member.all|join:", " }}</td>
                                <td>{{ project.project_memo }}</td>
                                <td>
                                    <button type="button" class="btn btn-success btn-xs modify" data-toggle="modal"
                                            data-id="{{ project.id }}" data-target="#ProjectModal">详细/更新
                                    </button>
                                    <a href="{% url 'org_chart' project.id %}" class="modaal-ajax" target="_blank">
                                        <button type="button" class="btn btn-info btn-xs">架构</button>
                                    </a>
                                    <button type="button" class="btn btn-danger btn-xs delete"
                                            data-id="{{ project.id }}">删除
                                    </button>
                                </td>
                            </tr>
                        {% endfor %}

                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

            <!-- ProjectModal  -->
            <div class="modal fade" id="ProjectModal" tabindex="-1" role="dialog" aria-labelledby="ProjectModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="ProjectModalLabel">

                            </h4>
                        </div>
                        {% if perms.projs.add_project and perms.projs.change_project %}
                            <div class="modal-body">
                                <form id="proj_info" class="main form-horizontal">
                                    <fieldset>
                                        <div class="form-group">
                                            <label for="project_name" class="col-sm-2 control-label"><span class="text-red">*</span>项目名称</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" name="project_name" maxlength="64"
                                                       id="project_name" required/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="project_env" class="col-sm-2 control-label"><span class="text-red">*</span>项目环境</label>
                                            <div class="col-sm-9">
                                                <select class="form-control select2" name="project_env" id="project_env"
                                                        style="width: 100%;" required>
                                                    {% for project_env in project_envs %}
                                                        <option value="{{ project_env.0 }}">{{ project_env.1 }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <!--div class="form-group">
                                            <label for="project_web" class="col-sm-2 control-label">项目网址</label>
                                            <div class="col-sm-9">
                                                <input type="text" class="form-control" name="project_web"
                                                       id="project_web"/>
                                            </div>
                                        </div-->

                                        <div class="form-group">
                                            <label for="project_product" class="col-sm-2 control-label">产品名称</label>
                                            <div class="col-sm-9">
                                                <select class="form-control select2" name="project_product" style="width: 100%;"
                                                       id="project_product" value=""/>
                                                    {% for project_product in project_products %}
                                                        <option value="{{ project_product.id }}">{{ project_product.product_name }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="project_admin" class="col-sm-2 control-label"><span class="text-red">*</span>项目负责人</label>
                                            <div class="col-sm-9">
                                                <select class="form-control select2" name="project_admin"
                                                        id="project_admin"
                                                        style="width: 100%;" required>
                                                    {% for project_user in project_users %}
                                                        <option value="{{ project_user.id }}">{{ project_user.username }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="project_member" class="col-sm-2 control-label">项目成员</label>
                                            <div class="col-sm-9">
                                                <select class="form-control select2" name="project_member"
                                                        multiple="multiple"
                                                        id="project_member" style="width: 100%;">
                                                    {% for project_user in project_users %}
                                                        <option value="{{ project_user.id }}">{{ project_user.username }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="project_memo" class="col-sm-2 control-label">项目备注</label>
                                            <div class="col-sm-9">
                                            <textarea class="form-control" name="project_memo"
                                                      id="project_memo"></textarea>
                                            </div>
                                        </div>
                                    </fieldset>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" id="proj_ops"></button>
                            </div>
                        {% else %}
                            <div class="modal-body">
                                抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                            </div>
                        {% endif %}
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>
        </div>
    </div>
    <!-- /.row -->

{% endblock %}


{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'modaal/js/modaal.min.js' %}"></script>
    <script src="{% static 'parsley/dist/parsley.min.js' %}"></script>
    <script src="{% static 'parsley/dist/zh_cn.js' %}"></script>

    <script>
        $(function () {
            proj_table = $('#proj-list').DataTable({
                language: {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "快速搜索:",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               },
                columnDefs: [{
                    'targets': [-1],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });
        });

        // Initialize Select2 Elements
        $(function () {
            $('.select2').select2({
                placeholder: "请选择",//必须要有否则单选点击清处按钮无效
                allowClear: true
            })
        });

        // 处理在modal中select2当选框无法搜索的问题
        $.fn.modal.Constructor.prototype.enforceFocus = function () {
        };

        // 查看架构图
        $('.modaal-ajax').modaal({
            type: 'ajax',
            width: 1000
        });


        let proj_tbody = $('#proj-list tbody');
        let proj_ops = $('#proj_ops');

        // 新增项目
        $('#add-proj').on('click', function () {
            document.getElementById('proj_info').reset();
            $('#proj_info').parsley().destroy();
            $(".select2").val('').trigger('change');
            $('#project_name').removeAttr("readonly");
            $('#project_env').removeAttr("disabled");
            $('.modal-title').text('新增项目');
            proj_ops.text('添加');

            proj_ops.unbind('click').on('click', function () {
                let data = $('#proj_info').serializeJson();
                let status = $('#proj_info').parsley().validate();
                if(status){
                    $.ajax({
                        url: '/api/project/',
                        type: 'POST',
                        data: JSON.stringify(data),
                        contentType: "application/json",
                        success: function () {
                            $('#ProjectModal').modal('hide')
                            $.alert({
                                title: 'Tips',
                                type: 'green',
                                content: "新增成功！",
                                buttons: {
                                       ok: function () {
                                           window.location.reload()
                                    },
                                },
                            })
                        },
                        error: function (response) {
                            if(response.responseJSON.hasOwnProperty('non_field_errors')){
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: "项目列表中的项目名称和项目环境的组合已经存在，请修改！",
                                })
                            } else {
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: '请修改错误！'+response.responseText,
                                })
                            }
                        }
                    });
                }
            })
        });

        // 更新项目
        proj_tbody.on('click', '.modify', function () {
            let proj_id = $(this).attr('data-id');
            $('.modal-title').text('修改项目信息');
            proj_ops.text('确认修改');
            $.get('/api/project/' + proj_id + '/', function (data) {
                $('#project_name').val(data.project_name);
                $('#project_env').val(data.project_env).trigger('change');
                $('#project_product').val(data.project_product).trigger('change');
                $('#project_admin').val(data.project_admin).trigger('change');
                $('#project_member').val(data.project_member).trigger('change');
                $('#project_memo').val(data.project_memo);
            });
            $('#project_name').attr('readonly', true);
            $('#project_env').attr('disabled', true);
            $('#proj_info').parsley().destroy();

            proj_ops.unbind('click').on('click', function () {
                let data = $('#proj_info').serializeJson();
                let status = $('#proj_info').parsley().validate();
                if(status){
                    $.ajax({
                        url: '/api/project/' + proj_id + '/',
                        type: 'PATCH',
                        data: JSON.stringify(data),
                        contentType: "application/json",
                        success: function () {
                            $('#ProjectModal').modal('hide')
                            $.alert({
                                title: 'Tips',
                                type: 'green',
                                content: "修改成功！",
                                buttons: {
                                       ok: function () {
                                           window.location.reload()
                                    },
                                },
                            })
                        },
                        error: function (response) {
                            if(response.responseJSON.hasOwnProperty('project_name')){
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: response.responseJSON.project_name,
                                })
                            } else {
                                $.alert({
                                    title: 'Tips',
                                    type: 'red',
                                    content: '请修改错误！'+response.responseText,
                                })
                            }
                        }
                    });
                }
            });
        });

        // 删除项目
        proj_tbody.on('click', '.delete', function () {
            {% if perms.projs.delete_project %}
                let pk = $(this).attr('data-id');
                let tr_obj = $(this).parents('tr');
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/project/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'green',
                                        content: '删除成功！',
                                        buttons: {
                                               ok: function () {
                                                   window.location.reload()
                                            },
                                        },
                                    })
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除项目的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 将数据JSON化
        (function ($) {
            $.fn.serializeJson = function () {
                let serializeObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (serializeObj[this.name]) {
                        if ($.isArray(serializeObj[this.name])) {
                            serializeObj[this.name].push(this.value);
                        } else {
                            serializeObj[this.name] = [serializeObj[this.name], this.value];
                        }
                    } else {
                        if (this.name.indexOf('project_member') !== -1) {
                            serializeObj[this.name] = [this.value];
                        }
                        else {
                            serializeObj[this.name] = this.value;
                        }
                    }
                });
                return serializeObj;
            };
        })(jQuery);
    </script>

{% endblock %}

